use std::collections::VecDeque;
use std::thread;
use std::thread::JoinHandle;

use log::{debug, error, info};

use crate::dto::task::{BatchTaskInfo, BizTask};
use crate::msghandler;
use crate::run::agent_run;

pub struct TaskPool {
    deque_h: VecDeque<Vec<BizTask>>,
    deque_l: VecDeque<Vec<BizTask>>,
    jh_l_op: Option<JoinHandle<()>>,
    jh_h_op: Option<JoinHandle<()>>,
}

impl TaskPool {
    pub fn new() -> TaskPool {
        return TaskPool {
            deque_h: VecDeque::new(),
            deque_l: VecDeque::new(),
            jh_l_op: None,
            jh_h_op: None,
        };
    }
    pub fn add(&mut self, bti: BatchTaskInfo) {
        if let Some(tasks) = bti.task_list {
            let mut h_task_list = Vec::new();
            let mut l_task_list = Vec::new();
            for task_info in tasks {
                let task = BizTask {
                    biz_code: task_info.biz_code,
                    data: task_info.data.clone(),
                    level: task_info.level,
                    order: task_info.order,
                    msg_id: task_info.msg_id,
                };
                if task.is_high_level() {
                    h_task_list.push(task)
                } else {
                    l_task_list.push(task)
                }
            }
            if !q_limited(&self.deque_h) {
                self.deque_h.push_front(h_task_list);
            }
            if !q_limited(&self.deque_l) {
                self.deque_l.push_front(l_task_list);
            }
        }
    }
    pub fn run(&mut self) {
        if q_has_task(&self.deque_h) {
            if let Some(ref jh) = self.jh_h_op {
                if jh.is_finished() {
                    if let Some(mut tasks) = self.deque_h.pop_back() {
                        self.jh_h_op = run_task_thread(tasks);
                    }
                } else {
                    debug!("有未执行完的H任务,等待上个任务完成");
                }
            } else {
                if let Some(mut tasks) = self.deque_h.pop_back() {
                    self.jh_h_op = run_task_thread(tasks);
                }
            }
        }

        //是否有低级别任务
        if q_has_task(&self.deque_l) {
            if let Some(ref jh) = self.jh_l_op {
                if jh.is_finished() {
                    if let Some(mut tasks) = self.deque_l.pop_back() {
                        self.jh_l_op = run_task_thread(tasks);
                    }
                } else {
                    debug!("有未执行完的L任务，等待上个任务完成");
                }
            } else {
                if let Some(mut tasks) = self.deque_l.pop_back() {
                    self.jh_l_op = run_task_thread(tasks);
                }
            }
        }
    }
}

fn run_task_thread(mut tasks: Vec<BizTask>) -> Option<JoinHandle<()>> {
    if tasks.len() <= 0 {
        return None;
    }
    let tname = format!("task-{}", &tasks[0].msg_id[10..]);
    let tb = thread::Builder::new().name(tname.clone());
    let hrt = tb.spawn(move || {
        tasks.sort_by(|a, b| a.order.cmp(&b.order));
        for task in tasks {
            info!("{tname}处理业务->{}-{}", task.biz_code,task.order);
            msghandler::handle_task(task)
        }
    });
    if let Ok(h) = hrt {
        Some(h)
    } else {
        None
    }
}

fn q_has_task(vd: &VecDeque<Vec<BizTask>>) -> bool {
    vd.len() > 0
}

fn q_limited(vd: &VecDeque<Vec<BizTask>>) -> bool {
    let b = vd.len() > 2024;
    if b {
        error!("任务队列满，不接受新任务")
    }
    b
}
